from numpy import array, pi, zeros
import numpy as N
import random

from qtAnimationWidget import *
import ecg

def concat(*args):
	return N.concatenate(args, axis=1)

class ECGCanvas(MatplotAnimationCanvas):
		
	index = 0
	dimension = 300
	ECGdimension = 150
	RRinterval = 50
	timer_tick = 200
	pixel_per_tick = 40

	# L'intervallo RR standard e' di 50 pixel.
	# Onda + intervallo = 200 pixel (un battito con pausa)
	# un battito deve stare in 1 secondo (60 battiti al minuto circa)
	# con un timer che scatta ogni 200 millisecondi..
	# ogni  tick mi muovo di 40 pixel
	# ---> 1 secondo     : 1 battito = 1 tick           : 1 passo per tick
	#      1000 millisec : 200 pixel = 200 millisecondi : 40 pixel

	"""A canvas that updates itself every second with a new plot."""
	def __init__(self, *args, **kwargs):
		self.observer =  kwargs['observer']
		del kwargs['observer']
		try:
			dir(self.observer).index('needOneMoreRR')
		except:
			raise AttributeError('observer object must have "needOneMoreRR" method.')

		MatplotAnimationCanvas.__init__(self, *args, **kwargs)

		self.timer = QtCore.QTimer(self)
		QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.update_figure)
		self.timer.start(self.timer_tick)

		self.compute_initial_figure()

	def compute_initial_figure(self):
		e = ecg.ecg(self.ECGdimension)
		self.ECGdata = concat( zeros(self.dimension*2), e, zeros(self.RRinterval))

		self.plotter, = self.axes.plot(self.ECGdata[0:self.dimension], 'r')
		self.axes.set_ybound(-.6,.8)
		self.axes.set_autoscaley_on(False)

	def update_figure(self):

		if len(self.ECGdata) < self.index+self.dimension:
			#print "add new ECG wave" 
			r = self.observer.needOneMoreRR()
			self.RRinterval = (r-50)*2
			e = ecg.ecg(self.ECGdimension) 
			self.ECGdata = concat( self.ECGdata, e, zeros(self.RRinterval) )#, e, zeros(self.RRinterval))

		i = self.index  
		d = i + self.dimension  
		
		self.plotter.set_ydata( self.ECGdata[i:d] )
		self.draw()
		
		self.index += self.pixel_per_tick
		

if __name__ == "__main__":
	import main.py
